package dict_controller

import (
	"github.com/gin-gonic/gin"
	"html/template"
	"net/http"
	dd "pear-admin-layui-go/app/sys/dict/domain"
	ds "pear-admin-layui-go/app/sys/dict/service"
	"pear-admin-layui-go/framework/login_filter"
	fr "pear-admin-layui-go/framework/result"
	ft "pear-admin-layui-go/framework/table"
	"strconv"
	"time"
)

func Enable(c *gin.Context) {
	var der dd.DictEnableRequest
	_ = c.ShouldBind(&der)
	user, _ := login_filter.GetCurrentUser(c)
	der.UpdateBy = user.Id
	der.UpdateName = user.Username
	der.UpdateTime = time.Now().Unix()
	db := ds.Enable(&der)
	fr.Result(c, db)
}

func Save(c *gin.Context) {
	var dsr dd.DictSaveRequest
	_ = c.ShouldBind(&dsr)
	user, _ := login_filter.GetCurrentUser(c)
	dsr.CreateBy = user.Id
	dsr.CreateName = user.Username
	dsr.CreateTime = time.Now().Unix()
	_, err := ds.Save(&dsr)
	fr.Result(c, err)
}

func Edit(c *gin.Context) {
	var der dd.DictEditRequest
	_ = c.ShouldBind(&der)
	user, _ := login_filter.GetCurrentUser(c)
	der.UpdateBy = user.Id
	der.UpdateName = user.Username
	der.UpdateTime = time.Now().Unix()
	db := ds.Edit(&der)
	fr.Result(c, db)
}

func Table(c *gin.Context) {
	var dsr dd.DictSearchRequest
	_ = c.ShouldBind(&dsr)
	dicts, count := ds.Table(&dsr)
	dictTable := make([]dd.DictTableResponse, len(dicts))
	for i, v := range dicts {
		dictTable[i] = dd.DictTableResponse{
			Id:         v.Id,
			TypeName:   v.TypeName,
			TypeCode:   v.TypeCode,
			Remark:     v.Remark,
			Enable:     v.Enable,
			CreateTime: v.CreateTime,
			CreateName: v.CreateName,
			UpdateTime: v.UpdateTime,
			UpdateName: v.UpdateName,
		}
	}
	c.JSON(http.StatusOK, ft.TableResponse{
		Data:  dictTable,
		Count: count,
	})
}

func Page(c *gin.Context) {
	c.HTML(http.StatusOK, "sys/dict/dict.html", gin.H{
		"dictEnable":     template.HTML("<input type='checkbox' value='{{d.id}}' lay-skin='switch' lay-text='启用|禁用' lay-filter='dict-type-enable' {{d.enable ? 'checked' : ''}}>"),
		"dictDataEnable": template.HTML("<input type='checkbox' value='{{d.id}}' lay-skin='switch' lay-text='启用|禁用' lay-filter='dict-data-enable' {{d.enable ? 'checked' : ''}}>"),
		"isDefault":      template.HTML("<input type='checkbox' value='{{d.id}}' lay-skin='switch' lay-text='启用|禁用' lay-filter='dict-data-isDefault' {{d.isDefault ? 'checked' : ''}}>"),
	})
}

func AddPage(c *gin.Context) {
	c.HTML(http.StatusOK, "sys/dict/add.html", gin.H{})
}

func EditPage(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	d := ds.EditPage(id)
	c.HTML(http.StatusOK, "sys/dict/edit.html", gin.H{
		"id":       d.Id,
		"typeName": d.TypeName,
		"typeCode": d.TypeCode,
		"remark":   d.Remark,
	})
}
